﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VirtualPress.Infrastructure.Entities.Entity;
using System.Web;
using VirtualPress.Infrastructure.Entities.Enum;
using VirtualPress.Engine.ExServer.WorkPool;
using VirtualPress.Engine.ExServer.WorkPool.WorkHandle.Email;
using VirtualPress.Infrastructure.Entities;
using VirtualPress.Infrastructure.Entities.Repository;
using System.IO;

namespace VirtualPress.Portal.Biz
{
    public class MagazineBiz
    {
        public static bool MagazineExamine(int articleId,int result,string msg)
        {
            var user = new User().Find(HttpContext.Current.User.Identity.Name);
            var article = new Article().Find(articleId.ToString());
            if (user == null || article == null)
            {
                return false;
            }
            var journal = new Periodical().Find(article.Peri_Id.ToString());
            if (journal == null || !(journal.Admin == HttpContext.Current.User.Identity.Name || user.SystemRole == UserRole.Admin))
            {
                return false;
            }
            if (result == 0)
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.Revise,
                    ManuscriptId = article.Id,
                    Message = "审核通过",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.Revise;
                article.PostModify();

                var record = new AuditingRecord().Find(c => c.ManuscriptId == article.Id);
                record.ExamineStatus = ExamineStatus.WanCheng;
                record.ExamineFinishDate = DateTime.Now;
                record.Message = "验收通过";
                record.PostModify();

                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                   new NormalNotifyEmail()
                   {
                       Recipient = article.UserName,
                       Message = String.Format("您的稿件《{0}》已终审核通过，编辑部方正在进行编辑校对，之后会与您取得联系。",article.Title)
                   });
            }
            else if (result == 9)
            {
                new ArticleHistory()
                {
                    CreateTime = DateTime.Now,
                    CurrentStatus = ArticleStatus.Close,
                    ManuscriptId = article.Id,
                    Message = "审核不通过",
                    Operator = HttpContext.Current.User.Identity.Name,
                    PreStatus = article.Status
                }.PostAdd();

                article.Status = ArticleStatus.Close;
                article.PostModify();

                var record = new AuditingRecord().Find(c => c.ManuscriptId == article.Id);
                record.ExamineStatus = ExamineStatus.WanCheng;
                record.ExamineFinishDate = DateTime.Now;
                record.Message = "验收不通过";
                record.PostModify();

                var att = new Appendix().FindLast(c => c.Type == (int)AttachmentType.Manuscript && c.RaletionId == article.Id);
                att.Suggestion = msg;
                att.PostModify();

                //给作者发邮件
                WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                    new NormalNotifyEmail()
                    {
                        Recipient = article.UserName,
                        Title = "您的稿件审核不通过",
                        Message = String.Format("您的稿件《{0}》审核不通过。<br/>{1}", article.Title, msg)
                    });
            }
            return true;
        }

        public static bool ExamineComplete(int articleId)
        {
            var user = new User().Find(HttpContext.Current.User.Identity.Name);
            var article = new Article().Find(articleId.ToString());
            if (user == null || article == null)
            {
                return false;
            }
            var journal = new Periodical().Find(article.Peri_Id.ToString());
            if (journal == null || !(journal.Admin == HttpContext.Current.User.Identity.Name || user.SystemRole == UserRole.Admin))
            {
                return false;
            }

            new ArticleHistory()
            {
                CreateTime = DateTime.Now,
                CurrentStatus = ArticleStatus.Complete,
                ManuscriptId = article.Id,
                Message = "编审校对完成",
                Operator = HttpContext.Current.User.Identity.Name,
                PreStatus = article.Status
            }.PostAdd();

            article.Status = ArticleStatus.Complete;
            article.PostModify();

            WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
               new NormalNotifyEmail()
               {
                   Recipient = article.UserName,
                   Message = String.Format("您的稿件《{0}》已终编辑校对完成，期刊方将在近期安排出版。", article.Title)
               });

            return true;
        }

        public static bool IsPublish(int articleId)
        {
            var user = new User().Find(HttpContext.Current.User.Identity.Name);
            var article = new Article().Find(articleId.ToString());
            if (user == null || article == null)
            {
                return false;
            }
            var journal = new Periodical().Find(article.Peri_Id.ToString());
            if (journal == null || !(journal.Admin == HttpContext.Current.User.Identity.Name || user.SystemRole == UserRole.Admin))
            {
                return false;
            }

            new ArticleHistory()
            {
                CreateTime = DateTime.Now,
                CurrentStatus = ArticleStatus.Publish,
                ManuscriptId = article.Id,
                Message = "已出版",
                Operator = HttpContext.Current.User.Identity.Name,
                PreStatus = article.Status
            }.PostAdd();

            article.Status = ArticleStatus.Publish;
            article.PostModify();
            return true;
        }

        #region 期刊出版
        public static MagazineItem NewJournalItem(int journalId, string manuscriptcode, string publishDate)
        {
            var journal = new Periodical().Find(journalId.ToString());
            var item = new MagazineItem()
                {
                    CreateDate = DateTime.Now,
                    Manuscriptcode = manuscriptcode,
                    PublishDate = DateTime.Parse(publishDate),
                    Status = JournalItemStatus.Create,
                    PeriodicalId = journalId
                };
            if (journal != null)
            {
                var file = System.Web.HttpContext.Current.Request.Files["Cover"];
                if (file != null && file.ContentLength > 0)
                {
                    string basedir = String.Format("/content/journal/{0}/{1}/cover/", journal.Name, manuscriptcode);
                    if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                    {
                        System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                    }
                    var fileinfo = new FileInfo(file.FileName);
                    string filePath = basedir + manuscriptcode + "-converimage" + fileinfo.Extension;
                    file.SaveAs(HttpContext.Current.Server.MapPath(filePath));
                    item.CoverImage = filePath;
                }

                item.PostAdd();
                return item;
            }
            return null;
        }
        public static void DeleteJournalItem(int journalId, int journalItemId)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var username = HttpContext.Current.User.Identity.Name;
                var user = new User().Find(username);
                var journal = new Periodical().Find(journalId.ToString());
                if (user != null && (username == journal.Admin || user.SystemRole == UserRole.Admin))
                {
                    var journalItem = new MagazineItem().Find(journalItemId.ToString());
                    if (journalItem != null)
                    {
                        journalItem.PostDelete();
                    }
                }
            }
        }
        public static List<MagazineItem> GetAllJournalItem(int journalId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data =(from c in ctx.MagazineItem
                           where c.PeriodicalId == journalId
                           orderby c.Id descending
                           select c)
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c=>new MagazineItem().Set(c))
                           .ToList();
                return data;
            }
        }
        public static int GetAllJournalItemForPage(int journalId)
        {
            return new PeriodicalItem().Count(c => c.Id == journalId);
        }
        public static List<MagazineItem> GetAllPublishJournalItem(int journalId, int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.MagazineItem
                            where c.PeriodicalId == journalId && c.Status == (int)JournalItemStatus.Publish
                            orderby c.Id descending
                            select c)
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new MagazineItem().Set(c))
                           .ToList();
                return data;
            }
        }
        public static int GetAllPublishJournalItemForPage(int journalId)
        {
            using (Context ctx = new Context())
            {
                return ctx.MagazineItem.Count(c => c.PeriodicalId == journalId && c.Status == (int)JournalItemStatus.Publish);
            }
        }
        public static List<Periodical> GetAllMagazines(int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Periodical
                            where c.IsActive && c.Type == (int)JournalType.nonscholastic
                            orderby c.Id descending
                            select c)
                           .Skip(page * pageSize)
                           .Take(pageSize)
                           .ToList()
                           .Select(c => new Periodical().Set(c))
                           .ToList();
                return data;
            }
        }
        public static int GetAllMagazinesForpage()
        {
            using (Context ctx = new Context())
            {
                return ctx.Periodical.Count(c => c.IsActive && c.Type == (int)JournalType.nonscholastic);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="journalItemId"></param>
        /// <returns>-1: 超过20MB，0:失败，1:成功，2:期刊被禁用 </returns>
        public static int PublishJournalItem(int journalItemId, string information)
        {
            var file = System.Web.HttpContext.Current.Request.Files["articles"];
            if (file != null && file.ContentLength > 0)
            {
                if (file.ContentLength > 1024 * 1024 * 20)
                {
                    return -1;
                }
                //string basedir = "/content/journal/" + journal.Name + "/coverimage/";
                //if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                //{
                //    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                //}
                //var fileinfo = new FileInfo(file.FileName);
                //string filePath = basedir + journal.Name + "-converimage" + fileinfo.Extension;
                //file.SaveAs(HttpContext.Current.Server.MapPath(filePath));
                //journal.CoverImg = filePath;
            }

            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var journalItem = new MagazineItem().Find(journalItemId.ToString());
                if (journalItem != null)
                {
                    var journal = new Periodical().Find(journalItem.PeriodicalId.ToString());
                    if (!journal.IsActive)
                    {
                        return 2;
                    }
                    string username = HttpContext.Current.User.Identity.Name;
                    var user = new User().Find(username);
                    if (user != null && (journal.Admin.ToLower() == username.ToLower() || user.SystemRole == UserRole.Admin))
                    {
                        string basedir = String.Format("/content/journal/{0}/{1}/pages/", journal.Name, journalItem.Manuscriptcode);
                        if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(basedir)))
                        {
                            System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(basedir));
                        }
                        var fileinfo = new FileInfo(file.FileName);
                        string filePath = basedir + journalItem.Manuscriptcode + "-more" + fileinfo.Extension;
                        file.SaveAs(HttpContext.Current.Server.MapPath(filePath));
                        journalItem.PagePath = filePath;
                        journalItem.Information = information;
                        journalItem.Status = JournalItemStatus.Publish;
                        journalItem.PostModify();
                    }
                    return 1;
                }
            }
            return 0;
        }
        #endregion
    }
}
